package com.hiwan.unions.activity.main;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hiwan.unions.R;
import com.hiwan.unions.activity.base.RootActivity;
import com.hiwan.unions.activity.loginRegister.LoginUserActivity;
import com.hiwan.unions.activity.main.fragment.fragmentController.FragmentController;
import com.hiwan.unions.application.AppManager;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.interfac.IService;
import com.hiwan.unions.application.receiver.TagAliasOperatorHelper;
import com.hiwan.unions.application.receiver.TagAliasOperatorHelper.TagAliasBean;
import com.hiwan.unions.application.request.CallServer;
import com.hiwan.unions.application.request.ConstsNet;
import com.hiwan.unions.application.request.HttpListener;
import com.hiwan.unions.application.service.LocalService;
import com.hiwan.unions.util.CheckUtils;
import com.hiwan.unions.util.JsonUtil;
import com.hiwan.unions.util.SystemUtil;
import com.hiwan.unions.util.ToastUtils;
import com.hiwan.unions.view.dialog.QiandaoDialog;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.TagAliasCallback;

import static com.hiwan.unions.application.receiver.TagAliasOperatorHelper.ACTION_SET;
import static com.hiwan.unions.application.receiver.TagAliasOperatorHelper.sequence;

public class MainActivity extends RootActivity implements HttpListener<JSONObject> {
    FragmentController controller;
    private RadioGroup group;
    private RadioButton my, home, event, nearby, button;
    public String typeFragment = "HomeFragment";
    private QiandaoDialog dialog;
    Request<JSONObject> request;
    private MsgReceiver msgReceiver;
    private MyServiceConnection conn = null;
    private IService iService = null;
    private Intent serviceIntent = null;

    @Override
    protected int getLayout() {
        title = false;
        return R.layout.activity_main;
    }

    public static void startPreview(Context context, Class c, String typeFragment) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("type", typeFragment);
        Intent intent2 = new Intent(context, c);
        Intent[] intents = {intent, intent2};
        context.startActivities(intents);
    }

    @Override
    protected void initData() {
        //动态注册广播接收器
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.communication.RECEIVER");
        registerReceiver(msgReceiver, intentFilter);
    }

    @Override
    protected void onViewCreated() {
        super.onViewCreated();
        conn = new MyServiceConnection();
        serviceIntent = new Intent(this, LocalService.class);
        bindService(serviceIntent, conn, Context.BIND_AUTO_CREATE);
        setUpMenu();
    }

    public static void startPreview(Activity context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    TagAliasCallback tagAlias = new TagAliasCallback() {
        @Override
        public void gotResult(int responseCode, String alias, Set<String> tags) {
            Logger.i("JFX_MainActivity已登陆" + "设置别名的结果为=" + alias + ",arg1=" + alias
                    + ",arg2=" + alias);
        }
    };

    private void setUpMenu() {
        try {
            TagAliasBean tagAliasBean = new TagAliasBean();
            tagAliasBean.action = ACTION_SET;
            tagAliasBean.alias = SystemUtil.getImei(this);
            tagAliasBean.isAliasAction = true;
            TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
            dialog = new QiandaoDialog(this);
            controller = FragmentController.getInstance(MainActivity.this, R.id.main_fragment);
            my = findView(R.id.my);
            home = findView(R.id.home);
            event = findView(R.id.event);
            nearby = findView(R.id.nearby);
            button = findView(R.id.button);
            group = findView(R.id.radiogrouproup);
            //绑定一个匿名监听器
            group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup arg0, int arg1) {
                    switch (arg1) {
                        case R.id.home:
                            typeFragment = "HomeFragment";
                            controller.showFragment(0);
                            break;
                        case R.id.event:
                            typeFragment = "EventFragment";
                            controller.showFragment(1);
                            break;
                        case R.id.nearby:
                            typeFragment = "NearbyFragment";
                            controller.showFragment(2);
                            break;
                        case R.id.button:
                            typeFragment = "WorkersFragment";
                            controller.showFragment(3);
                            break;
                        case R.id.my:
                            Logger.i("执行aaa ");
                            typeFragment = "MyFragment";
                            if (CheckUtils.userInfo(userInfo)) {
                                controller.showFragment(4);
                            } else {
                                LoginUserActivity.startPreview(MainActivity.this);
                            }
                            break;
                        default:
                            break;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        dimss();
        if (userInfo.getBoolean(ConstantsValues.IS_HASLOGIN, false)) {
            request = NoHttp.createJsonObjectRequest(ConstsNet.sign, RequestMethod.POST);
            request.add("city", userInfoC.getString(ConstantsValues.CITYNAMEOne, ""));
            CallServer.getRequestInstance().addToken(this, 0, request, this, true, userInfo);
        }
    }

    public void setDimss() {
        LoginUserActivity.startPreview(this);
    }

    private void dimss() {
        if (CheckUtils.userInfo(userInfo)) {
        } else {
            if (typeFragment.equals("MyFragment")) {
                typeFragment = "HomeFragment";
            }
        }
        if (typeFragment.equals("HomeFragment")) {
            home.setChecked(true);
        } else if (typeFragment.equals("MyFragment")) {
            my.setChecked(true);
            controller.showFragment(4);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        controller.onDestroy();
        //注销广播
        unregisterReceiver(msgReceiver);
        if (conn != null) {
            unbindService(conn);
            conn = null;
        }

    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getInstance(this).AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void cityName() {
        super.cityName();
        if (typeFragment.equals("NearbyFragment") || typeFragment.equals("EventFragment")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    controller.cityName();
                }
            });
        }
    }

    @Override
    public void onSucceed(int what, Response<JSONObject> response) {
        JSONObject jsonObject = response.get();
        jsonObject = JsonUtil.getJSONObject(jsonObject, "data");
        switch (what) {
            case 0:
                SharedPreferences.Editor editor = userInfo.edit();
                editor.putString(ConstantsValues.points, JsonUtil.getString(jsonObject, "points"));
                editor.commit();
                dialog.show(JsonUtil.getString(jsonObject, "points"));
                break;
        }

    }


    @Override
    public void onFailed(int what, int errCode, String networkMillis, boolean type) {
        switch (what) {
            case 0:
                if (errCode == 500) {
                    ToastUtils.showToast();
                }
                break;
        }
    }

    //
    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //拿到在服务里面实现了IService接口的Binder对象
            iService = (IService) service;
            Logger.i("IService  " + "我被拿到了");
            iService.invokeServiceMethod(true);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);//must store the new intent unless getIntent() will return the old one
        intent = getIntent();
        if (intent.getStringExtra("type") != null)
            typeFragment = intent.getStringExtra("type");

    }

    /**
     * 广播接收器
     *
     * @author len
     */
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            controller.cityNames();
        }
    }
}